// #ifdef H5
import jweixin from 'static/js/jweixin.js'
// #endif
import request from 'static/request'
import util from 'static/util'
import config from '../config/config'

uni.setStorageSync('signPackageExpiration',0);

export default {
    //判断是否在微信中  
    isWechat: function() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/micromessenger/i) == 'micromessenger') {
            // console.log('是微信客户端')
            return true;
        } else {
            // console.log('不是微信客户端')
            return false;
        }
    },
    //初始化sdk配置  
    initJssdkShare: function(callback, callback2) {
		var that = this;
		if (!this.isWechat()) {  return callback2 && callback2(); }
		// #ifdef H5
		var expiration = (Date.parse(new Date()) / 1000) - uni.getStorageSync('signPackageExpiration');
		if(expiration > 3600){
			request('/common/Wxapi/getSignPackage',{
				url:  location.origin +  location.pathname,
			},true).then(res =>  {
				var result = res.data;
				jweixin.config({
					debug: false,
					appId: result.appId,
					timestamp: result.timestamp,
					nonceStr: result.nonceStr,
					signature: result.signature,
					jsApiList: [
					  'checkJsApi',
					  'onMenuShareTimeline',
					  'onMenuShareAppMessage',
					  // 'onMenuShareQQ',
					  // 'onMenuShareWeibo',
					  // 'hideMenuItems',
					  // 'showMenuItems',
					  // 'hideAllNonBaseMenuItem',
					  // 'showAllNonBaseMenuItem',
					  // 'translateVoice',
					  // 'startRecord',
					  // 'stopRecord',
					  // 'onRecordEnd',
					  // 'playVoice',
					  // 'pauseVoice',
					  // 'stopVoice',
					  // 'uploadVoice',
					  // 'downloadVoice',
					  // 'chooseImage',
					  // 'previewImage',
					  // 'uploadImage',
					  // 'downloadImage',
					  // 'getNetworkType',
					  'openLocation',
					  'getLocation',
					  'hideOptionMenu',
					  'showOptionMenu',
					  // 'closeWindow',
					  // 'scanQRCode',
					  'chooseWXPay',
					  'openProductSpecificView',
					  'addCard',
					  'chooseCard',
					  'openCard'
					]
				});
				//配置完成后，再执行功能  
				jweixin.ready(function() {
					uni.setStorageSync('signPackageExpiration',result.timestamp);
					if (callback) { callback(result); }
				});
			});
		}else{
			jweixin.ready(function() {
				if (callback) { callback(); }
			});
		}
		// #endif
    },
    // 自定义分享功能- 在需要自定义分享的页面中调用  
	// this.$wechat.share({ title:1, desc:2, img:1 })
    share: function(data, url) {
        //每次都需要重新初始化配置，才可以进行分享  
        this.initJssdkShare(function(signData) {
			var shareData = {
			    title: data && data.title ? data.title : signData.site_name,
			    desc: data && data.desc ? data.desc : signData.site_description,
			    link: url || location.href,
			    imgUrl: data && data.img ? data.img : signData.site_logo,
			    success: function(res) {
			        // 分享后的一些操作,比如分享统计等等
			    },
			    cancel: function(res) {}
			};
			//分享给朋友接口  
			jweixin.onMenuShareAppMessage(shareData);
			//分享到朋友圈接口  
			jweixin.onMenuShareTimeline(shareData);
        });
    },
	// -----
	// 获取当前地理位置
	// -----
	getLocation:function(callback,isGetText,callback2){
		//  获取地址
		// #ifdef H5
			this.initJssdkShare(function(signData) {
				jweixin.getLocation({
					type:"gcj02",// 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02
					success: function (res) {
						if(callback) { 
							if(isGetText){
								request("/common/Wxapi/getLocation",{
									latitude:res.latitude,
									longitude:res.longitude,
								},false).then(res=>{
									callback(res)
								})
							}else{
								callback(res)
							}
						}
					},
					cancel: function (res) {
						alert('请给权限使用位置信息');
					}
				});
			},callback2);
		// #endif
		
		//  获取地址
		// #ifdef MP-WEIXIN
			wx.getLocation({
				type: 'gcj02',
				isHighAccuracy:true,
				success: function (res) {
					if(callback) {
						if(isGetText){
							request("/common/Wxapi/getLocation",{
								latitude:res.latitude,
								longitude:res.longitude,
							},false).then(res=>{
								callback(res)
							})
						}else{
							callback(res)
						}
					}
				}
			});
		// #endif
		
	},
	// -----
	// 调用付款
	// -----
	chooseWXPay(param={},callback){
		// #ifdef MP-WEIXIN
		param.web_mode = 'wx_app';
		// #endif
		request("/common/Wxapi/wxPay",param,true).then(res=>{
			// #ifdef H5
			function onBridgeReady() {
				WeixinJSBridge.invoke('getBrandWCPayRequest', {
					appId: res.data.appId ,
					timeStamp: ""+ res.data.timeStamp,
					nonceStr: res.data.nonceStr,
					signType:"MD5",
					package: res.data.package,
					paySign: res.data.paySign,
				},(res)=>{
					if (res.err_msg === 'get_brand_wcpay_request:ok') {
						if(callback){
							callback();
						}else if(param.parent_page == "orderDetail"){
							uni.navigateBack();
						}else if(param.parent_page == "member" ){
							
						} else{
							uni.reLaunch({ url: '/pages/order/orderDetail?order_no='+ param.order_no });
						}
					} else {
						uni.showToast({
							icon: 'none',
							position:"top",
							title:"支付失败",
						});
					}
				});
			} 
			if (typeof WeixinJSBridge == "undefined"){
			   if( document.addEventListener ){
				   document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			   }else if (document.attachEvent){
				   document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
				   document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			   }
			}else{
			   onBridgeReady();
			}
			// #endif
			
			// #ifdef MP-WEIXIN
			wx.requestPayment({
				appId: res.data.appId,
				timeStamp:"" +res.data.timeStamp,
				nonceStr: res.data.nonceStr,
				signType:"MD5",
				package: res.data.package,
				paySign: res.data.paySign,
				success:function(res){
					if(callback){
						callback();
					}if(param.parent_page == "orderDetail"){
						uni.navigateBack();
					}else if(param.parent_page == "member" ){
						
					} else{
						uni.reLaunch({ url: '/pages/order/orderDetail?order_no='+ param.order_no });
					}
				},
				fail:function(res){
					uni.showToast({
						icon: 'none',
						position:"top",
						title:"支付失败",
					});
				}
			}) 
			// #endif
		});
	}
}


